package com.ikas.ai.server.module.flow.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ikas.ai.framework.core.event.NodeEvent;
import com.ikas.ai.framework.core.listener.NodeListener;
import com.ikas.ai.framework.flow.ScoreFlow;
import com.ikas.ai.framework.node.Node;
import com.ikas.ai.framework.node.NodeStatus;
import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.server.module.flow.model.FlowNodeExec;
import com.ikas.ai.server.module.flow.service.FlowNodeExecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description: 流程节点listener
 * @Author: qi.yilai
 * @Date: 2023/2/1 15:32
 * @Version: 1.0.0
 **/
@Component
public class MaintainNodeListener implements NodeListener {

    @Autowired
    private FlowNodeExecService flowNodeExecService;

    @Override
    public boolean fireEvent(NodeEvent event) {
        Node node = event.getOwner();
        ScoreFlow scoreFlow = node.getOwner();

        FlowNodeExec flowNodeExec = new FlowNodeExec();
        flowNodeExec.setId(node.nodeInstanceId());
        flowNodeExec.setNodeId(node.nodeId());
        flowNodeExec.setSceneId(scoreFlow.getSceneId());
        flowNodeExec.setFlowId(scoreFlow.getFlowId());
        flowNodeExec.setFlowInstanceId(scoreFlow.getFlowInstanceId());

        NodeStatus nodeStatus = node.status();
        flowNodeExec.setStatus(nodeStatus.getStatus().byteValue());

        switch (nodeStatus) {
            case STARTING:
                flowNodeExec.setStartTime(new Date(node.startTime()));
                flowNodeExec.setUpdateTime(new Date());
                break;
            case SUCCESS:
                flowNodeExec.setEndTime(new Date(node.endTime()));
                Object result = node.result();
                if (result instanceof JSONObject) {
                    flowNodeExec.setResult(JSON.toJSONString(node.result().toString(), SerializerFeature.WriteBigDecimalAsPlain, SerializerFeature.WriteMapNullValue));
                } else {
                    flowNodeExec.setResult(result.toString());
                }
                flowNodeExec.setUpdateTime(new Date());
                flowNodeExec.setInputParam(JSON.toJSONString(node.previous(), SerializerFeature.WriteBigDecimalAsPlain, SerializerFeature.WriteMapNullValue));
                break;
            case FAILURE:
                flowNodeExec.setEndTime(new Date());
                flowNodeExec.setUpdateTime(new Date());
                break;
            default:
                throw new BusinessException("流程节点状态不合法");
        }
        flowNodeExecService.updateById(flowNodeExec);
        return true;
    }
}
